﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Pibby.Controls
{
	public class WatermarkedTextBox : TextBox
	{
		private string _watermarkText;

		public WatermarkedTextBox()
		{
			this._watermarkText = "<Watermark>";

			this.TextChanged += new EventHandler(WatermarkedTextBox_TextChanged);
			this.LostFocus += new EventHandler(WatermarkedTextBox_LostFocus);
		}

		protected override void OnCreateControl()
		{
			base.OnCreateControl();
			CheckWatermarkStatus();
		}

		void WatermarkedTextBox_LostFocus(object sender, EventArgs e)
		{
			CheckWatermarkStatus();
		}

		void WatermarkedTextBox_TextChanged(object sender, EventArgs e)
		{
			CheckWatermarkStatus();
		}

		public string WatermarkText
		{
			get { return this._watermarkText; }
			set { this._watermarkText = value; Invalidate(); }
		}


		private void CheckWatermarkStatus()
		{
			if (this.Text.Length <= 0)
				this.SetWatermark(this.WatermarkText);
			else
				this.SetWatermark(string.Empty);

			Invalidate();
		}

		private void SetWatermark(string watermark)
		{
			NativeMethods.SendMessage(this.Handle, EM_SETCUEBANNER, 0, watermark);
		}

		#region WinAPI 

		const uint ECM_FIRST = 0x1500;
		const uint EM_SETCUEBANNER = ECM_FIRST + 1;

		private static class NativeMethods
		{
			[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
			public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);
		}
	
		#endregion WinAPI
	}
}
